package com.android.fragmentdemo.thread3

import org.junit.Test
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveTask

class Demo3 {
    @Test
    fun testForkJoin() {
        val forkJoinPool = ForkJoinPool(8)
        val dataList = mutableListOf<Int>()
        for (i in 0..100) {
            dataList.add(i)
        }

        val batchInsertTask = BatchInsertTask(dataList)
        val t1 = System.currentTimeMillis()
        val result = forkJoinPool.submit(batchInsertTask)
        println("result:${result.get()}")
        val t2 = System.currentTimeMillis()
        println("times:${t2 - t1}")
    }

    class BatchInsertTask(records: MutableList<Int>) : RecursiveTask<Int>() {

        private val mRecords = records

        override fun compute(): Int {
            val size = mRecords.size
            return if (size < 3) {
                computeDirectly()
            } else {
                val task0 = BatchInsertTask(mRecords.subList(0, size / 2))
                val task1 = BatchInsertTask(mRecords.subList(size / 2, size))
                //两个任务并发执行起来
                invokeAll(task0, task1)
                return task0.join() + task1.join()
            }
        }

        private fun computeDirectly() : Int {
            try {
                Thread.sleep(mRecords.size * 1000L)
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            }
            println("插入了:${mRecords.toIntArray().contentToString()}")
            return mRecords.size
        }
    }
}